package com.common.tools;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;

/**
 * 短信下发工具类
 * 
 * @author chenlujun
 * @version [版本号, 2014年12月11日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class SmsTools {
	
	/**
	 * 手机短信下发
	 * 
	 * @param phoneNo
	 *            手机号
	 * @param content
	 *            短信内容
	 * @return 短信运营商短信下发ID
	 * @see [类、类#方法、类#成员]
	 */
	public static String sendsms(String phoneNo, String content) {

		if (StringTools.isNull(phoneNo)) {
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "手机号为空");
		}

		if (StringTools.isNull(content)) {
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "短信内容为空");
		}
		content+="【PAC】";

		String url = PropertyUtils.getValue("sms.28inter.url");
		String userid = PropertyUtils.getValue("sms.28inter.userid");
		String account = PropertyUtils.getValue("sms.28inter.account");
		String password = PropertyUtils.getValue("sms.28inter.password");

		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType",
				"application/x-www-form-urlencoded;charset=UTF-8");

		NameValuePair[] data = { new NameValuePair("userid", userid),
				new NameValuePair("account", account),
				new NameValuePair("password", password),
				new NameValuePair("mobile", phoneNo),
				new NameValuePair("content", content),
				new NameValuePair("sendTime", "") };
		method.setRequestBody(data);

		try {
			client.executeMethod(method);
			String SubmitResult = method.getResponseBodyAsString();
			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();
			String message = root.elementText("message");
			String returnstatus = root.elementText("returnstatus");
			String taskID = root.elementText("taskID");
			if ("Success".equals(returnstatus)) {
				return taskID;
			} else {
				throw new LogicException(ErrorNumber.ERROR_MESSAGE, message);
			}

		} catch (HttpException e) {
			throw new LogicException(ErrorNumber.SYSTEM_ERROR, e.getMessage());
		} catch (IOException e) {
			throw new LogicException(ErrorNumber.SYSTEM_ERROR, e.getMessage());
		} catch (DocumentException e) {
			throw new LogicException(ErrorNumber.SYSTEM_ERROR, e.getMessage());
		}
	}

}
